package com.example.su_shi_tan_mine.child

import android.text.Editable
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.utils.normalShortToast
import com.example.su_shi_tan_bas_lib.album.Album
import com.example.su_shi_tan_bas_lib.base.BaseFragmentEx
import com.example.su_shi_tan_bas_lib.base.BaseLazyDataBindingFragment
import com.example.su_shi_tan_bas_lib.glidmodule.GlideApp
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.OnTextListener
import com.example.su_shi_tan_bas_lib.utils.upload_file.UploadFileWorker
import com.example.su_shi_tan_core.arouter.MineARouter
import com.example.su_shi_tan_core.db.UserInfoBean
import com.example.su_shi_tan_core.db.UserInfoBeanHolder
import com.example.su_shi_tan_core.getUserInfo
import com.example.su_shi_tan_mine.R
import com.example.su_shi_tan_mine.databinding.IdentifyVerifyFragmentBinding

/**
 * 实名认证
 * */
@Route(path = MineARouter.IDENTIFY_VERIFY)
class IdentifyVerifyFragment : BaseLazyDataBindingFragment<IdentifyVerifyFragmentBinding>(),
    View.OnClickListener, OnTextListener {


    private var frontPicStr = ""

    private var oppositePicStr = ""

    private var identifyNameStr = ""

    private var identifyCodeStr = ""

    private var mUploadFileWorker: UploadFileWorker? = null


    override fun layoutId(): Int {
        return R.layout.identify_verify_fragment
    }

    override fun lazyInit() {

    }

    override fun initView(view: View) {
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "实名认证"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.onViewClick = this
        viewBinder.onTextListener = this

        val userInfo = UserInfoBeanHolder.getUserInfoBean()

        if (userInfo?.verifyStrFlag() == UserInfoBean.checkedYes || userInfo?.verifyStrFlag() == UserInfoBean.checking) {
            loadData(userInfo)
            mToolbar.title = "实名认证 - (${userInfo.verifyStr()})"
        }
    }

    private fun loadData(userInfo: UserInfoBean) {

        viewBinder.verifyTv.visibility = View.GONE

        viewBinder.frontPicSelector.visibility = View.GONE
        viewBinder.frontPic.visibility = View.VISIBLE
        viewBinder.frontPic.isEnabled = false
        GlideApp.with(this)
            .load(userInfo.card_pros_url)
            .into(viewBinder.frontPic)

        viewBinder.oppositePicSelector.visibility = View.GONE
        viewBinder.oppositePic.visibility = View.VISIBLE
        viewBinder.oppositePic.isEnabled = false
        GlideApp.with(this)
            .load(userInfo.card_cons_url)
            .into(viewBinder.oppositePic)



        viewBinder.identifyName.isEnabled = false
        viewBinder.identifyName.setText(userInfo.real_name)

        viewBinder.identifyCode.isEnabled = false
        viewBinder.identifyCode.setText(userInfo.card_id)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.front_Pic_Selector, R.id.front_Pic -> {
                Album.getInstance()
                    .singleImage(true)
                    .onSuccess {
                        if (it.isNotEmpty()) {
                            v.visibility = View.GONE
                            viewBinder.frontPic.visibility = View.VISIBLE
                            frontPicStr = it[0].path
                            GlideApp.with(this)
                                .load(frontPicStr)

                                .into(viewBinder.frontPic)
                        }
                    }
                    .onFailed { _, msg ->
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }
                    .execute(childFragmentManager)
            }
            R.id.opposite_Pic_Selector, R.id.opposite_Pic -> {
                Album.getInstance()
                    .singleImage(true)
                    .onSuccess {
                        if (it.isNotEmpty()) {
                            v.visibility = View.GONE
                            viewBinder.oppositePic.visibility = View.VISIBLE
                            oppositePicStr = it[0].path
                            GlideApp.with(this)
                                .load(oppositePicStr)
                                .into(viewBinder.oppositePic)
                        }
                    }
                    .onFailed { _, msg ->
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }
                    .execute(childFragmentManager)
            }

            R.id.verifyTv -> {
                if (checkInfo()) {
                    viewBinder.mProgressBar.visibility = View.VISIBLE
                    viewBinder.verifyTv.visibility = View.GONE

                    val mutableListOf = mutableListOf<String>()
                    mutableListOf.add(frontPicStr)
                    mutableListOf.add(oppositePicStr)

                    mUploadFileWorker = UploadFileWorker()
                    mUploadFileWorker?.isOnlyFileName = true
                    mUploadFileWorker?.setListener(object : UploadFileWorker.UpLoadOverListener {
                        override fun onUpLoadOver(res: List<String>) {
                            mUploadFileWorker = null
                            onSending(res)
                        }
                    })?.doWork(mutableListOf)
                }
            }
        }
    }

    private fun onSending(res: List<String>) {
        if (res.isEmpty() || res.size < 2) {
            Toast.makeText(_mActivity, "图片上传失败", Toast.LENGTH_SHORT).show()
            viewBinder.mProgressBar.visibility = View.GONE
            viewBinder.verifyTv.visibility = View.VISIBLE
            return
        }


        val maps = mapOf(
            "card_pros_url" to res[0],
            "card_cons_url" to res[1],
            "card_id" to identifyCodeStr,
            "real_name" to identifyNameStr
        )
        RestClient.builder()
            .url(R.string.checkIdCard)
            .raw(JSON.toJSONString(maps))
            .raw(JSON.toJSONString(maps))
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
                getUserInfo(_mActivity)
            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
                viewBinder.mProgressBar.visibility = View.GONE
                viewBinder.verifyTv.visibility = View.VISIBLE
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                viewBinder.mProgressBar.visibility = View.GONE
                viewBinder.verifyTv.visibility = View.VISIBLE
            }
            .build()
            .post()
    }

    private fun checkInfo(): Boolean {
        var flag = true

        when {
            identifyNameStr.isEmpty() -> {
                flag = false
                normalShortToast(_mActivity, "请输入真实姓名")

            }
            identifyCodeStr.isEmpty() || identifyCodeStr.length < 18 -> {
                flag = false
                normalShortToast(_mActivity, "请输入正确身份证号")
            }
            frontPicStr.isEmpty() -> {
                flag = false
                normalShortToast(_mActivity, "请选择正面照片")

            }
            oppositePicStr.isEmpty() -> {
                flag = false
                normalShortToast(_mActivity, "请选择反面照片")

            }
        }


        return flag
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.identifyName -> {
                identifyNameStr = s.toString()
            }
            R.id.identifyCode -> {
                identifyCodeStr = s.toString()
            }
        }
    }


}